<?php

class Core_Backend_Component_Road_Controller_Info extends Dcmp_Component_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function indexAction($pageindex = 1, $pagesize = 20, $sort = 'id', $dir = 'asc') {
        $this->getHistory()->record();
        $validator = new Kd_Validation_Validator();
        $validator->setTarget($this->getRequest()->getParameter('filter'));
        $collection = App::getModel('road/collection_info')
                        ->joinAccount()
                        ->filterByRole($this->getIdentity()->getRoleIds('road'))
                        ->sortBy($sort, $dir)
                        ->pagination($pageindex, $pagesize);
        if ($validator->isNotEmpty('name')) {
            $collection->filterByName($validator->getValue('name'));
        }
        if ($validator->isNotEmpty('status')) {
            $collection->filterByStatus($validator->getValue('status'));
        }
        $collection->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function editAction($code) {
        $model = App::getModel('road/info')->loadByCode($code);
        return $this->viewResult(array('model' => $model));
    }

    public function submitPostAction() {
        return $this->saveModel('pending', TRUE);
    }

    public function savePostAction() {
        return $this->saveModel('draft', TRUE);
    }

    public function applyPostAction() {
        return $this->saveModel('draft');
    }

    private function saveModel($status, $return = FALSE) {
        $data = $this->getRequest()->getForm('info');
        $model = App::getModel('road/info');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data);
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__f('share.message.saveSuccess', '{road.label.info}', $model->getRoadName()));
            return $return ?
                    $this->redirectResult($this->getHistoryUrl('road/info/index')) :
                    $this->redirectResult($this->getUrl(array('code' => $model->getCode()), 'edit'));
        } else {
            $this->getMessager()->addError($this->__f('share.message.saveFail', '{road.label.info}', $model->getRoadName()))->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

}
